import { ImmerReducer, Effect } from 'umi';
import { getProductApi } from '@/api/product';

export type Istate = {
  // 定义state接口
  productList: Object[] | [];
  err: string | null;
};

export type productModelType = {
  // 定义model接口
  namespace: string;
  state: Istate;
  reducers: {
    setProductList: ImmerReducer<Istate>; // ImmerReducer用来方便的更新状态
  };
  effects: {
    getProductList: Effect;
  };
};

const productModel: productModelType = {
  namespace: 'product', //  命名空间
  state: {
    productList: [],
    err: null,
  },
  reducers: {
    //
    setProductList(state, action) {
      state.productList = action.payload.data;
      state.err = action.payload.err;
    },
  },
  effects: {
    //  副作用：相当于vuex中的actions
    *getProductList({ payload }, { call, put }): any {
      // 获取数据
      yield new Promise((resolve, rejrct) => {
        setTimeout(() => {
          resolve(1234);
        }, 2000);
      });
      try {
        let res = yield call(getProductApi);
        yield put({
          type: 'setProductList',
          payload: { data: res.data, err: null },
        });
      } catch (e: any) {
        console.log(e);
        yield put({
          type: 'setProductList',
          payload: { data: [], err: e.toString() },
        });
      }
    },
  },
};

export default productModel;
